package leetcode.day_2021_03_22_2021_03_28;

import java.util.ArrayList;
import java.util.List;

/**
 * 77. 组合
 * https://leetcode-cn.com/problems/combinations/
 */
public class LeetCode0077 {
    List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> combine(int n, int k) {
        List<Integer> list = new ArrayList<>();
        boolean[] used = new boolean[n+1];
        backtrack(n, k, 1, list, used);
        return res;
    }

    public void backtrack(int n, int k, int begin, List<Integer> list, boolean[] used) {
        if (list.size() == k) {
            res.add(new ArrayList<>(list));
            return;
        }

        for (int i=begin; i<=n; i++) {
            if (list.size()!=0 && list.get(list.size()-1)>=i){
                continue;
            }
            if (used[i]) {
                continue;
            }
            list.add(i);
            used[i] = true;
            backtrack(n, k, begin+1, list, used);
            list.remove(list.size()-1);
            used[i] = false;
        }
    }
}
